package cn.bs.seckill.service.impl;


import cn.bs.seckill.exception.GlobalException;
import cn.bs.seckill.mapper.UserMapper;
import cn.bs.seckill.pojo.User;
import cn.bs.seckill.service.UserService;
import cn.bs.seckill.utils.CookieUtil;
import cn.bs.seckill.utils.MD5Util;
import cn.bs.seckill.utils.RedisUtil;
import cn.bs.seckill.utils.UUIDUtil;
import cn.bs.seckill.vo.LoginVo;
import cn.bs.seckill.vo.RespBean;
import cn.bs.seckill.vo.RespBeanEnum;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 布索
 * @since 2022-02-17
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public RespBean doLogin(LoginVo loginVo, HttpServletRequest request, HttpServletResponse response) {
        String mobile = loginVo.getMobile();
        String password = loginVo.getPassword();

/*        //判断账号密码是否为空
        if (StringUtils.isEmpty(mobile)||StringUtils.isEmpty(password)) {
            return RespBean.error(RespBeanEnum.LOGIN_ERROR);
        }
        //判断是否正确输入手机号
        if (!ValidatorUtil.isMobile(mobile)){
            return RespBean.error(RespBeanEnum.LOGIN_FAILED);
        }*/
        User user = userMapper.selectById(mobile);
        //判断手机号是否存在
     /*   if (null==user){
            return RespBean.error(RespBeanEnum.LOGIN_FAILED);
        }*/
        if (null==user){
            throw new GlobalException(RespBeanEnum.LOGIN_FAILED);
        }
        //判断密码是否正确
      /*  if (!(user.getPassword()).equals(MD5Util.toDBPassEpt(password))){
            return RespBean.error(RespBeanEnum.LOGIN_FAILEDP);
        }*/
        if (!(user.getPassword()).equals(MD5Util.toDBPassEpt(password))){
            throw new GlobalException(RespBeanEnum.LOGIN_FAILEDP);
        }

        //生成cookie
        String uuid = UUIDUtil.uuid();
        //把uuid和用户的登录信息存入session
        request.getSession().setAttribute(uuid,user);
        //将用户信息存入redis
        redisUtil.set("user:"+uuid,user);
        //设置cook的值
        CookieUtil.setCookie(request,response,"userUUID",uuid);
        return RespBean.success();
    }

    @Override
    public User getUserByCookie(String userUUID) {
        if (StringUtils.isEmpty(userUUID)){
            return null;
        }
        //拿到用户信息
        User user =(User) redisUtil.get("user:" + userUUID);

        return user;
    }
}
